<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { GetDataDetail, PostBrandofficialConfig } from '@/api/modules/brandofficial'
// import { GetOptionData as GetCouponOption } from '@/api/modules/voucher'
// import { GetAllData as GetProductOption } from '@/api/modules/merchandiseControl'

const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()

const ruleForm: any = ref({
  introPic: '',
  actNoticeText: '',
  actIntroPic: '',
  qvCodePic: '',
  subjectSetting: {
    id: 0,
    topbgPic: '',
    topProducts: '',
    bannerTxt: '',
    extendProducts: '',
  },
})

// const OptionObj = reactive({
// couponOption: [] as any[],
// productOption: [] as any[],
// })

const rules = reactive({
  'introPic': [
    { required: true, message: '请上传介绍图', trigger: 'blur' },
  ],
  'actNoticeText': [
    { required: true, message: '请输入活动通知文本', trigger: 'blur' },
  ],
  'actIntroPic': [
    { required: true, message: '请输入活动介绍', trigger: 'blur' },
  ],
  'qvCodePic': [
    { required: true, message: '请上传企微二维码', trigger: 'blur' },
  ],
  'ticketSetting.shareTxt': [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
  'ticketSetting.sharePic': [
    { required: true, message: '请上传分享图', trigger: 'blur' },
  ],
  'subjectSetting.topbgPic': [
    { required: true, message: '请上传顶部背景图', trigger: 'blur' },
  ],
  'subjectSetting.bannerTxt': [
    { required: true, message: '请上传文字分栏图', trigger: 'blur' },
  ],
  'ticketSetting.bannerPic': [
    { required: true, message: '请上传顶部banner图', trigger: 'blur' },
  ],
  'ticketSetting.bannerTxtPic': [
    { required: true, message: '请上传分栏图', trigger: 'blur' },
  ],
  'ticketSetting.ruleBtnPic': [
    { required: true, message: '请上传活动规则按钮图', trigger: 'blur' },
  ],
  'ticketSetting.rulePic': [
    { required: true, message: '请上传活动规则图', trigger: 'blur' },
  ],
  'ticketSetting.ticketBgpic': [
    { required: true, message: '请上传券背景图', trigger: 'blur' },
  ],
  'ticketSetting.ticketId': [
    { required: true, message: '请选择优惠券', trigger: 'blur' },
  ],
  'ticketSetting.shareBtnPic': [
    { required: true, message: '请上传分享按钮图', trigger: 'blur' },
  ],
  'ticketSetting.qrcodeBtnPic': [
    { required: true, message: '请上传二维码按钮图', trigger: 'blur' },
  ],
  'ticketSetting.qrcodeBgpic': [
    { required: true, message: '请上传二维码背景图', trigger: 'blur' },
  ],
  'ticketSetting.status': [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  'ticketSetting.productIds': [
    { required: true, message: '请选择关联商品', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, objKey?: string, listKey?: string) {
  if (objKey) {
    if (listKey) {
      ruleForm.value[objKey][listKey][Number(key)].pic = url
    }
    ruleForm.value[objKey][key] = url
  }
  else {
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  // console.log(ruleForm.value)
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
      }
      params.subjectSetting.topProducts = JSON.stringify(ruleForm.value.subjectSetting.topProducts)
      params.subjectSetting.extendProducts = JSON.stringify(ruleForm.value.subjectSetting.extendProducts)

      // console.log(params)

      PostBrandofficialConfig(params).then((res: any) => {
        if (res.statusCode === 200) {
          ElMessage.success('品牌官编辑成功')
          GetDataDetail().then((res) => {
            ruleForm.value = res.data
            if (ruleForm.value.subjectSetting.topProducts) {
              ruleForm.value.subjectSetting.topProducts = JSON.parse(ruleForm.value.subjectSetting.topProducts)
            }
            else {
              ruleForm.value.subjectSetting.topProducts = []
            }
            if (ruleForm.value.subjectSetting.extendProducts) {
              ruleForm.value.subjectSetting.extendProducts = JSON.parse(ruleForm.value.subjectSetting.extendProducts)
            }
            else {
              ruleForm.value.subjectSetting.extendProducts = []
            }
            ruleForm.value.ticketSetting.productIds = ruleForm.value.ticketSetting.productIds.split(',').map((item: any) => {
              return Number(item)
            })
          })
        }
        else {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
      })
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

function AddCard(key: string) {
  if (key === 'topProducts') {
    ruleForm.value.subjectSetting.topProducts.push({ pic: '', url: '' })
  }
  else if (key === 'extendProducts') {
    ruleForm.value.subjectSetting.extendProducts.push({ pic: '', url: '' })
  }
  else {
    ElMessage.error('添加出错')
  }
}

function DeleteItem(index: number, key: string) {
  ruleForm.value.subjectSetting[key].splice(index, 1)
}

onMounted(async () => {
  try {
    await GetDataDetail().then((res) => {
      ruleForm.value = res.data

      // 处理双重序列化的 JSON 字符串
      const parseNestedJson = (str: string) => {
        if (!str) {
          return []
        }
        try {
          // 先尝试直接解析
          const parsed = JSON.parse(str)
          // 如果解析后还是字符串，说明有双重序列化，需要再解析一次
          if (typeof parsed === 'string') {
            return JSON.parse(parsed)
          }
          return parsed
        }
        catch (e) {
          console.error('解析失败:', e)
          return []
        }
      }

      // 处理 topProducts
      ruleForm.value.subjectSetting.topProducts
    = parseNestedJson(ruleForm.value.subjectSetting.topProducts)

      // 处理 extendProducts
      ruleForm.value.subjectSetting.extendProducts
    = parseNestedJson(ruleForm.value.subjectSetting.extendProducts)
    })
    // await GetCouponOption('1').then((res) => {
    //   OptionObj.couponOption = res.data
    // })

    // await GetProductOption().then((res) => {
    //   OptionObj.productOption = res.data
    // })
  }
  catch (error) {
    console.error(error)
  }
})
</script>

<template>
  <div>
    <PageHeader title="品牌官" />
    <ElForm ref="ruleFormRef" label-position="top" :model="ruleForm" :rules="rules">
      <PageMain title="品牌官配置">
        <ElRow :gutter="20">
          <ElCol :md="24">
            <ElFormItem label="活动通知文本" prop="actNoticeText">
              <el-input v-model="ruleForm.actNoticeText" placeholder="请输入活动通知文本" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动介绍" prop="actIntroPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.actIntroPic" @on-success="(url: string) => handleUploadSuccess(url, 'actIntroPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="介绍图" prop="introPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.introPic" @on-success="(url: string) => handleUploadSuccess(url, 'introPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="上传企微二维码" prop="qvCodePic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.qvCodePic" @on-success="(url: string) => handleUploadSuccess(url, 'qvCodePic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <div style="display: grid; grid-template-columns: 2fr 1fr; margin-top: -15px;">
        <PageMain title="专题页配置">
          <ElRow :gutter="20">
            <ElCol :md="12">
              <ElFormItem label="顶部背景图" prop="subjectSetting.topbgPic">
                <ImageUpload
                  :ext="['jpg', 'png']" height="100" width="auto" :size="5"
                  :url="ruleForm.subjectSetting.topbgPic" @on-success="(url: string) => handleUploadSuccess(url, 'topbgPic', 'subjectSetting')"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :md="12">
              <ElFormItem label="文字分栏图" prop="subjectSetting.bannerTxt">
                <ImageUpload
                  :ext="['jpg', 'png']" height="100" width="auto" :size="5"
                  :url="ruleForm.subjectSetting.bannerTxt" @on-success="(url: string) => handleUploadSuccess(url, 'bannerTxt', 'subjectSetting')"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :md="24">
              <ElFormItem label="顶部商品">
                <div v-if="ruleForm.subjectSetting?.topProducts?.length === 0" class="mb-5 text-right">
                  <el-button type="success" @click="AddCard('topProducts')">
                    添加
                  </el-button>
                </div>
                <div class="card-box">
                  <el-card v-for="(item, index) in ruleForm.subjectSetting.topProducts" :key="index" shadow="hover">
                    <ElFormItem label="路径">
                      <el-input v-model="item.url" placeholder="请输入路径" />
                    </ElFormItem>
                    <ElFormItem label="上传图片">
                      <ImageUpload
                        :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                        :url="item.pic" @on-success="(url) => handleUploadSuccess(url, `${index}`, 'subjectSetting', 'topProducts')"
                      />
                    </ElFormItem>
                    <template #footer>
                      <div class="text-right">
                        <el-button :disabled="ruleForm.subjectSetting.topProducts?.length > 1" type="success" @click="AddCard('topProducts')">
                          添加
                        </el-button>
                        <el-button type="danger" @click="DeleteItem(index, 'topProducts')">
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-card>
                </div>
              </ElFormItem>
            </ElCol>
            <ElCol :md="24">
              <ElFormItem label="推广商品">
                <div v-if="ruleForm.subjectSetting?.extendProducts?.length === 0" class="mb-5 text-right">
                  <el-button type="success" @click="AddCard('extendProducts')">
                    添加
                  </el-button>
                </div>
                <div class="card-box">
                  <el-card v-for="(item, index) in ruleForm.subjectSetting.extendProducts" :key="index" shadow="hover">
                    <ElFormItem label="路径">
                      <el-input v-model="item.url" placeholder="请输入路径" />
                    </ElFormItem>
                    <ElFormItem label="上传图片">
                      <ImageUpload
                        :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                        :url="item.pic" @on-success="(url) => handleUploadSuccess(url, `${index}`, 'subjectSetting', 'extendProducts')"
                      />
                    </ElFormItem>
                    <template #footer>
                      <div class="text-right">
                        <el-button :disabled="ruleForm.subjectSetting.extendProducts?.length > 4" type="success" @click="AddCard('extendProducts')">
                          添加
                        </el-button>
                        <el-button type="danger" @click="DeleteItem(index, 'extendProducts')">
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-card>
                </div>
              </ElFormItem>
            </ElCol>
          </ElRow>
        </PageMain>
        <PageMain title="专题页预览">
          <ElRow :gutter="20">
            <div class="box">
              <div class="box-header">
                <div class="head-bg">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting?.topbgPic" fit="fill" />
                </div>
                <div class="head-content">
                  <div class="content-head">
                    <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting?.topProducts[0]?.pic" fit="fill" />
                  </div>
                  <div class="content-body">
                    <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting?.topProducts[1]?.pic" fit="fill" />
                  </div>
                </div>
              </div>
              <div class="banner">
                <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.bannerTxt" fit="fill" />
              </div>
              <div class="body">
                <div class="img1">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.extendProducts[0]?.pic" fit="fill" />
                </div>
                <div class="img2">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.extendProducts[1]?.pic" fit="fill" />
                </div>
                <div class="img3">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.extendProducts[2]?.pic" fit="fill" />
                </div>
                <div class="img4">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.extendProducts[3]?.pic" fit="fill" />
                </div>
                <div class="img5">
                  <el-image style="width: 100%; height: 100%;" :src="imgDomain + ruleForm.subjectSetting.extendProducts[4]?.pic" fit="fill" />
                </div>
              </div>
            </div>
          </ElRow>
        </PageMain>
      </div>
    </ElForm>
    <div style="height: 90px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style scoped>
/* stylelint-disable-next-line no-empty-source */
.box {
  width: 750px;

  .box-header {
    position: relative;
    width: 100%;
    height: 476px;

    .head-bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      width: 100%;
      height: 100%;
    }

    .head-bg img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      object-position: center;
    }

    .head-content {
      position: absolute;
      top: 244px;
      left: 31px;
      z-index: 2;
      display: flex;

      .content-head {
        width: 194px;
        height: 194px;
        margin-right: 13px;
      }

      .content-body {
        width: 481px;
        height: 194px;
      }
    }
  }

  .banner {
    width: 553px;
    height: 47px;
    margin-top: 20px;
    margin-left: 97px;
  }

  .body {
    display: grid;
    grid-template-rows: 160px 160px 160px;
    grid-template-columns: 335px 335px;
    grid-gap: 15px 19px;
    margin-top: 22px;
    margin-left: 31px;
  }

  /* .body div {
    background-color: red;
  } */

  .img1 {
    grid-row: span 2;
    grid-column: 1;
    height: 335px;
  }

  .img2 {
    grid-row: 3;
    grid-column: 1;
  }

  .img3 {
    grid-row: 1;
    grid-column: 2;
  }

  .img4 {
    grid-row: 2;
    grid-column: 2;
  }

  .img5 {
    grid-row: 3;
    grid-column: 2;
  }
}

.card-box {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}
</style>
